package com.woyowodaows.fragment.home;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.paradoxie.autoscrolltextview.VerticalTextview;
import com.woyowodaows.R;
import com.woyowodaows.activity.MainActivity;
import com.woyowodaows.activity.home.LoginActivity;
import com.woyowodaows.activity.home.NewNoticeDetailsActivity;
import com.woyowodaows.activity.mine.NewCentreActivity;
import com.woyowodaows.activity.mine.OrderInformationActivity;
import com.woyowodaows.activity.mine.ServiceManagementActivity;
import com.woyowodaows.adapter.home.HomeOrderAdapter;
import com.woyowodaows.base.BaseFragment;
import com.woyowodaows.bean.home.BannerInfoBean;
import com.woyowodaows.bean.home.BannerInfoDataBean;
import com.woyowodaows.bean.home.NearRepairBean;
import com.woyowodaows.bean.home.NearRepairData;
import com.woyowodaows.bean.home.NewNoticeBean;
import com.woyowodaows.bean.home.NoticeBean;
import com.woyowodaows.bean.home.NoticeData;
import com.woyowodaows.bean.home.OrderInfo;
import com.woyowodaows.bean.mine.UserInfoBean;
import com.woyowodaows.request.HttpAsyncTask;
import com.woyowodaows.request.HttpRequestListener;
import com.woyowodaows.request.InterfaceUrl;
import com.woyowodaows.utils.CacheUserInfoUtils;
import com.woyowodaows.utils.DisplayUtils;
import com.woyowodaows.utils.LoginJudge;
import com.woyowodaows.utils.SPUtils;
import com.woyowodaows.utils.ToastUtil;
import com.woyowodaows.viewholder.HomePageViewHolder;
import com.woyowodaows.viewholder.OnScrollTextListeners;
import com.woyowodaows.weight.LoadingDataLayout;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.R.id.message;

public class HomePageFragment extends BaseFragment {

    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.sw_refresh)
    SwipeRefreshLayout swRefresh;
    @BindView(R.id.iv_no_data)
    ImageView iVDaTa;
    @BindView(R.id.tv_state_bar)
    TextView tvStateBar;
    @BindView(R.id.rl_load)
    LoadingDataLayout rlLoad;


    private HomeOrderAdapter mAdapter;
    private List<OrderInfo> orderList=new ArrayList<>();
    private HomePageViewHolder homePageViewHolder;
    private List<BannerInfoBean> listImags = new ArrayList<>();
    private List<String> imageUrls=new ArrayList<>();

    private List<String> mScrollTextlist;//滚动广告
    private int scrollTextPosition = 0;
    private List<NoticeBean> mAdList=new ArrayList<NoticeBean>();;
    private  int Position;
    private Map<String, Object> mapParameter;



    private static final int SCROLL_AD = 0;//会员轮播广告
    public static final int DEFAULT_SCROLL_INTERVAL = 3000;//会员轮播广告间隔时间
    public static final int DEFAULT_SCROLL_ANIMATION_TIME = 500;//会员轮播广告动画时长

    private ArrayList<String> list=new ArrayList<String>();

    private VerticalTextview tvAd;
    private List<NearRepairBean> repairList=new ArrayList<>();
    private UserInfoBean userInfoBean;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    tvAd.setTextList(list);
                      tvAd.setText(18, 2, Color.WHITE);//设置属性
                      tvAd.setTextStillTime(3000);//设置停留时长间隔
                       tvAd.setAnimTime(1000);//设置进入和退出的时间间隔
                       tvAd.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
                           @Override
                           public void onItemClick(int position) {
                               Intent intent=new Intent(mContext, NewNoticeDetailsActivity.class);
                               Bundle bundle=new Bundle();
                               bundle.putSerializable("news",mAdList.get(position));
                               intent.putExtras(bundle);
                               startActivity(intent);
                           }
                       });
                    tvAd.startAutoScroll();
                    break;

            }
        }
    };

    @Override
    protected void initView() {
        ButterKnife.bind(this, layoutView);
        View headView = LayoutInflater.from(mContext).inflate(R.layout.layout_home_head, null);
        homePageViewHolder = new HomePageViewHolder(mContext, headView);
        tvAd=homePageViewHolder.tvAd;
        swRefresh.setColorSchemeResources(R.color.color_text_main);
        mAdapter=new HomeOrderAdapter();
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        rvData.setLayoutManager(layoutManager);
        rvData.setAdapter(mAdapter);
        getNearRepairData();
        getBannerImgs();
        mAdapter.addHeaderView(headView);
        swRefresh.post(new Runnable() {

            @Override
            public void run() {
                swRefresh.setRefreshing(true);
            }
        });
        //设置沉浸状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            tvStateBar.setVisibility(View.VISIBLE);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtils.getStatusBarHeight(mContext));
            tvStateBar.setLayoutParams(lp);
        }
        getNoticeData();//查询公告

        homePageViewHolder.tvNews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginJudge.isLogin(mContext, NewCentreActivity.class, null);
            }
        });

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener<NearRepairBean>() {
            @Override
            public void onItemClick(BaseQuickAdapter<NearRepairBean, ? extends BaseViewHolder> adapter, View view, int position) {
                boolean isLogin = (boolean) SPUtils.get(mContext, SPUtils.IS_LOGIN, false);
                if (!isLogin) {
                  startActivity(new Intent(mContext, LoginActivity.class));
                }else {
                    NearRepairBean bean= repairList.get(position);
                    Intent intent=new Intent(mContext,OrderInformationActivity.class);
                    intent.putExtra("OrderSn",bean.getOrderSn());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        mScrollTextlist = new ArrayList<>();
    }

    @Override
    public void initEvent() {
        super.initEvent();


        homePageViewHolder.baBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                BannerInfoBean bean = listImags.get(position);
//                if (bean.getJump() == 2) {
//                    return;
//                }

//                Intent intent = new Intent(mContext, AboutMeActivity.class);
//                intent.putExtra("title", bean.getName());
//                intent.putExtra("url", bean.getAurl());
//                intent.putExtra("banner","0");
//                startActivity(intent);
            }
        });
            rlLoad.setOnReloadListener(new LoadingDataLayout.OnReloadListener() {
                @Override
                public void onReload(View v, int status) {
                    rlLoad.setStatus(LoadingDataLayout.LOADING);
                    isRefresh = true;
                    pageNumber = 0;
                    maxPage = 1;
                    getNearRepairData();
                    getBannerImgs();
                }
            });
            swRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    isRefresh = true;
                    pageNumber = 0;
                    maxPage = 1;
                    getBannerImgs();
                    getNearRepairData();
                }
            });
            mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    if (maxPage <= pageNumber) {
//                        iVDaTa.setVisibility(View.GONE);
                        mAdapter.loadMoreEnd();
                    } else {
                        isRefresh = false;
                        pageNumber++;
                        getNearRepairData();
                    }
                }
            }, rvData);
//        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_page;
    }
    //获取近期订单
    public void getNearRepairData() {
        final int tempPageNum = pageNumber;
        final int tempPageSize = pageSize;
         mapParameter = new HashMap<>();
       final boolean isLogin = (boolean) SPUtils.get(mContext, SPUtils.IS_LOGIN, false);
            mapParameter.put("pageNumber", pageNumber);
            mapParameter.put("pageSize", pageSize);

        HttpAsyncTask.getInstance().onPostParam(mContext, "", false,InterfaceUrl.NEARREPAIR,NearRepairData.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    NearRepairData bean = (NearRepairData) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                        if (isRefresh) {
                            repairList.clear();
                            maxPage = bean.getData().getTotalPage();
                        }
                        if(bean.getData().getList().size()>0){
                            repairList.addAll(bean.getData().getList());
                            if (!isLogin) {
                                repairList.clear();
                                mAdapter.notifyDataSetChanged();
                                iVDaTa.setVisibility(View.VISIBLE);
                            }else {
                                mAdapter.setNewData(repairList);
                                iVDaTa.setVisibility(View.GONE);
                            }

                        }else {
                            swRefresh.setRefreshing(false);
                            mAdapter.loadMoreComplete();
                        }

                    } else {
                        pageSize = tempPageSize;
                        pageNumber = tempPageNum;
                        ToastUtil.showError(getActivity(), bean.getMessage());
                    }
                }
                swRefresh.setRefreshing(false);
               mAdapter.loadMoreComplete();

            }

            @Override
            public void onError(String message) {
                pageSize = tempPageSize;
                pageNumber = tempPageNum;
                swRefresh.setRefreshing(false);
                mAdapter.loadMoreFail();

            }
        });

    }

    //获取banner 数据
    private void getBannerImgs() {
        Map<String, Object> mapParameter = new HashMap<>();
          //offset:0启动页 1首页广告 2个人中心
        mapParameter.put("offset", "1");
        HttpAsyncTask.getInstance().onPostParam(mContext, "", false, InterfaceUrl.BANNDER, BannerInfoDataBean.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    BannerInfoDataBean bean = (BannerInfoDataBean) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                        if (bean.getData().size() > 0) {
                            if (isRefresh) {
                                listImags.clear();
                                imageUrls.clear();
                            }
                            listImags.addAll(bean.getData());
                            getBaner();
                        }
                    }
                }
            }

            @Override
            public void onError(String message) {
            }
        });


    }
    private  void getBaner(){
        for (int i = 0; i < listImags.size(); i++) {
            BannerInfoBean beans = listImags.get(i);
            imageUrls.add(beans.getVisitUrl());
        }
        homePageViewHolder.baBanner.setImages(imageUrls);
        homePageViewHolder.baBanner.start();
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }
    @Override
    public void onResume() {
        super.onResume();
        if (list!=null &&list.size()>0){
            tvAd.startAutoScroll();
        }
        boolean isLogin = (boolean) SPUtils.get(mContext, SPUtils.IS_LOGIN, false);
        if (!isLogin) {
            repairList.clear();
            mAdapter.notifyDataSetChanged();
            iVDaTa.setVisibility(View.VISIBLE);
        }else {
            iVDaTa.setVisibility(View.GONE);
            userInfoBean= CacheUserInfoUtils.getUserInfo();
            if(userInfoBean!=null){
                if(userInfoBean.getMsgs()>0){
                    homePageViewHolder.tvNews.setBackgroundResource(R.mipmap.icon_news_on);
                }else {
                    homePageViewHolder.tvNews.setBackgroundResource(R.mipmap.icon_news_off);
                }
            }
           getNearRepairData();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
//        boolean isLogin = (boolean) SPUtils.get(mContext, SPUtils.IS_LOGIN, false);
//        if (!isLogin) {
//            tvAd.setVisibility(View.GONE);
//        }else{
//            tvAd.setVisibility(View.VISIBLE);
           if(list.size()>0){
               tvAd.stopAutoScroll();
           }

//        }
    }

    public void getNoticeData() {
        Map<String, Object> mapParameter = new HashMap<>();
        HttpAsyncTask.getInstance().onPostParam(mContext, "", false, InterfaceUrl.QUERYNEARNOTICE, NoticeData.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    final NoticeData bean = (NoticeData) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                        if (bean.getData().size() > 0) {
                            mAdList.addAll(bean.getData());
                            if (isRefresh) {
                                list.clear();
                            }
                            for (NoticeBean lt:mAdList){
                                list.add(lt.getTitle());
                            }
                            if (list.size()>0){
                                handler.sendEmptyMessage(1);
                                }
//                            if(list.size()>0){
//                                homePageViewHolder.tvAd.setTextList(list);
//                                homePageViewHolder.tvAd.setText(18, 2, Color.WHITE);//设置属性
//                                homePageViewHolder.tvAd.setTextStillTime(3000);//设置停留时长间隔
//                                homePageViewHolder.tvAd.setAnimTime(1000);//设置进入和退出的时间间隔
//                                homePageViewHolder.tvAd.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
//                                    @Override
//                                    public void onItemClick(int position) {
//                                        Intent intent=new Intent(mContext, NewNoticeDetailsActivity.class);
//                                        Bundle bundle=new Bundle();
//                                        bundle.putSerializable("news",mAdList.get(position));
//                                        startActivity(intent);
//                                    }
//                                });
//
//                            }

                        }
                    }
                }
            }

            @Override
            public void onError(String message) {
            }
        });

    }


}
